package com.hardydou.learn.datasource;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * DsAspect
 *
 * @author hardy
 */

@Slf4j
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DsAspect {
    @Pointcut("@within(com.hardydou.learn.datasource.DS)")
    public void dsPointcut() {
    }

    @Around("dsPointcut()")
    public Object point(ProceedingJoinPoint point) throws Throwable {
        point.getSignature().getClass();
        DS clszzDs = AnnotationUtils.getAnnotation(point.getTarget().getClass(), DS.class);
        DS methodDs = AnnotationUtils.getAnnotation(((MethodSignature) point.getSignature()).getMethod(), DS.class);
        String ds = "";
        if (methodDs != null) {
            ds = methodDs.value();
        } else if (clszzDs != null) {
            ds = clszzDs.value();
        }
        if (StrUtil.isNotEmpty(ds)) {
            DynamicContextHolder.push(ds);
            log.info("set datasource {} !", ds);
        }
        try {
            return point.proceed();
        } finally {
            DynamicContextHolder.poll();
            log.info("clean datasource");
        }


    }
}
